﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StoreTransport.DAO;
using StoreTransport.Business.Helper;

namespace StoreTransport.Presentation.Forms {
    public partial class EditUser : Form {
        int id = 0;
        public EditUser() {
            InitializeComponent();
        }

        private void EditUser_Load(object sender, EventArgs e) {
            _gbxChangePass.Visible = false;
            MDIMainForm main = (MDIMainForm)this.MdiParent;
            if (main.user != null) {
                id = main.user.ID;
            }
            User selectedItem = CommonHelper.GetContext().Users.FirstOrDefault(c => c.ID.Equals(id));
            if (selectedItem != null) {
                _lblLoginName.Text = selectedItem.Username;
                _lblUserName.Text = selectedItem.Name;
                _lblRole.Text = selectedItem.Role1.RoleName;
            } else {
                _btnChangePassWord.Visible = false;
            }
        }

        private void _btnChangePassWord_Click(object sender, EventArgs e) {
            _tbxPassword.Select();
            _gbxChangePass.Visible = true;
        }

        private void _btxSavePassWord_Click(object sender, EventArgs e) {
            string errorMessage = CommonHelper.CheckRequiredField(_tbxPassword.Text, _lblPassword.Text);
            errorMessage += CommonHelper.CheckRequiredField(_tbxPasswordConfirm.Text, _lblPasswordConfirm.Text);
            if (!string.IsNullOrEmpty(errorMessage)) {
                MessageBox.Show(errorMessage);
                return;
            }
            errorMessage += CommonHelper.CheckRequiredField(_tbxPassword.Text, _lblPassword.Text);
            if (!string.IsNullOrEmpty(errorMessage)) {
                MessageBox.Show(errorMessage);
                return;
            }
            if (!_tbxPassword.Text.Equals(_tbxPasswordConfirm.Text)) {
                MessageBox.Show(StoreTransport.Resources.StoreTransportResource.ErrorMessage_PasswordConfirmNotMatch);
                return;
            }
            StoreTransportDataContext context = CommonHelper.GetContext();
            User selectedItem = context.Users.Where(c => c.ID.Equals(id)).First();
            selectedItem.Password = _tbxPassword.Text;
            context.SubmitChanges();
            _gbxChangePass.Visible = false;
        }
    }
}
